import { Group } from "three";
import { LoadGLB } from "./LoaderUtils";


export let ResPath: string = "";
//'https://btri-dev.midea.com/web/hvsp-editor/'
class ResCache {
    private __modelcache: Map<string, Group> = new Map();
    private __loadCB: Map<string, any[]> = new Map();
    constructor() {
        
    }

    getModel(filename: string, onLoad: (group: Group | undefined, fromCache?: boolean) => void) {
        if(ResPath === "") {
            console.error("ResPath not Set e. https://btri-dev.midea.com/web/hvsp-editor/")
            return;
        }

        if (this.__modelcache.has(filename)) {
            let copy = this.__modelcache.get(filename)?.clone()
            onLoad(copy, true);
        }
        else {
            if (this.__loadCB.has(filename)) {
                this.__loadCB.get(filename)?.push(onLoad);
                return;
            }
            this.__loadCB.set(filename, [onLoad]);
            const url = filename.startsWith("http") ? filename : "./model/" + filename;

            LoadGLB(ResPath + url, (root: Group | undefined) => {
                if (root) {
                    this.__modelcache.set(filename, root);
                    this.__loadCB.get(filename)?.forEach(cb => {
                        let copy = root.clone()
                        cb(copy);
                    })
                }

                this.__loadCB.delete(filename)
            })
        }

    }

}

export const resCache = new ResCache();